package com.pms.web;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.pms.controller.BaseController;
import com.pms.entity.*;
import com.pms.exception.R;
import com.pms.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  前端控制器
 *  1）户室面积，用于物业费生成=》可在 导入户主信息时导入批量修改
 *  2）物业费模板 => 可通过  其他绑定方式 绑定，避免添加户室 必须生成  收费模板。
 *  3)户室对应的楼层 不能修改，只能在 添加 删除
 *  4) 每层楼 每层楼最多创建99个户室
 * </p>
 *
 * @author ASUS_B
 * @since 2017-10-24
 */
@RestController
@RequestMapping("/unitHouseBase")
@Api(value="户室管理界面接口",description = "户室管理界面接口")
public class UnitHouseController extends BaseController {
    @Autowired
    private IEstateAgencyService agencyService;
    @Autowired
    private IUnitBuildingService unitBuildingService;
    @Autowired
    private IUnitFloorService unitFloorService;
    @Autowired
    private IUnitHouseService unitHouseService;
    @Autowired
    private IHouseMasterInfoService houseMasterInfoService;
    @Autowired
    IChargeTemplateService chargeTemplateService;

    @ApiOperation(value = "添加户室")
    @RequestMapping(value = "/addHouse",method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name="floorId",value="楼层id",required = true,dataType = "long",paramType="form"),
            @ApiImplicitParam(name="addHouseNum",value="户室添加数量(默认为1)",required = false,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="propertyId",value="物业费模板id",required = false,dataType = "long",paramType="form"),
            @ApiImplicitParam(name="houseRemarks",value="备注信息",required = false,dataType = "string",paramType="form"),
            @ApiImplicitParam(name="isShowApp",value="app是否显示(默认为1-显示，2-不显示)",required = false,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="houseProportion",value="户室面积(/户)",required = false,dataType = "double",paramType="form"),
    })
    public R addHouse(Long floorId, Long propertyId, Integer addHouseNum,String houseRemarks,Integer isShowApp,Double houseProportion){
        if(null!=houseProportion&&houseProportion<0){return R.error(400,"户室面积必须大于0");}
        parameterIsNull(floorId,"请选择楼层");
        UnitFloor floor = unitFloorService.selectById(floorId);
        parameterIsNull(floor,"暂无该楼层信息");
        UnitBuilding unit = unitBuildingService.selectById(floor.getUnitId());
        if(null==unit){//没有单元信息  残余数据
            return R.error(400,"残缺数据，请联系管理员");
        }
        ChargeTemplate chargeTemplate= null;
        if(null!=propertyId){
            chargeTemplate=  chargeTemplateService.selectById(propertyId);
            if(null==chargeTemplate){return R.error(400,"没有该收费模板信息");}
        }
        if(null==addHouseNum||addHouseNum<1){addHouseNum = 1;}
        if(null==isShowApp||isShowApp!=2){isShowApp = 1;}
        int floorHouseNum = unitHouseService.selectCount(new EntityWrapper<UnitHouse>().eq("floor_id",floorId));
        if((floorHouseNum+addHouseNum)>99){return R.error(400,"每层楼最多创建99个户室");}
        List<UnitHouse> addHouseList = new ArrayList<UnitHouse>();
        for(int x=1;x<=addHouseNum;x++){
            UnitHouse addHouse = new UnitHouse();
            addHouse.setCommunityId(floor.getCommunityId());
            addHouse.setFloorId(floor.getFloorId());
            addHouse.setHouseRemarks(houseRemarks);
            addHouse.setIsShowApp(isShowApp);
            addHouse.setChargeTemplateId(propertyId);
            addHouse.setUnitName(unit.getUnitName());
            addHouse.setUnitId(unit.getUnitId());
            addHouse.setAgencyId(floor.getAgencyId());
            addHouse.setHouseProportion(houseProportion);
            addHouse.setIsHaveMaster(2);//设置未导入户主
            addHouse.setIsHaveMember(2);//设置没有会员认证
            addHouse.setHouseSort(floorHouseNum+x);
            addHouse.setFloorSort(floor.getFloorSort());
            addHouse.setIsEstateHouse(2);//设置不是物业办公室
            if(addHouse.getHouseSort()<10){
                addHouse.setHouseNumber(floor.getFloorSort()+"0"+addHouse.getHouseSort());
            }
            if(addHouse.getHouseSort()>9){
                addHouse.setHouseNumber(floor.getFloorSort()+""+addHouse.getHouseSort());
            }
            if(null == addHouse.getChargeTemplateId() ){
                addHouse.setIsHavaChargeTemplate(2);//设置未配置物业费模板
            }
            if(null!=addHouse.getChargeTemplateId()){
                addHouse.setIsHavaChargeTemplate(1);//设置已配置物业费模板
                addHouse.setChargeTemplateName(chargeTemplate.getChargeTemplateName());
            }
            addHouseList.add(addHouse);
        }
        unitHouseService.insertBatch(addHouseList);
        // 同步清除 查询单元楼层户室的缓存
        unitFloorService.clearPreKeyCache("unitHouse:selectUnitFloorHouse");
        return R.ok();
    }


    @ApiOperation(value = "单独删除户室")
    @RequestMapping(value = "/delHouse",method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name="houseId",value="户室id",required = true,dataType = "long",paramType="form"),
    })
    public R delFloor(Long houseId){
        parameterIsNull(houseId,"请选择要删除的户室");
        UnitHouse delHouse = unitHouseService.selectById(houseId);
        parameterIsNull(delHouse,"该户室信息已删除");
        if(null!=delHouse.getIsHaveMember()&&delHouse.getIsHaveMember()==2){ return R.error(400,"该户室已有会员认证，无法删除");}
        int countFloorHouseNum = unitHouseService.selectCount(new EntityWrapper<UnitHouse>().eq("floor_id",delHouse.getFloorId()));
        if(delHouse.getHouseSort()<countFloorHouseNum){return R.error(400,"请先从本楼层房号最大的数据依次删除");}
        unitHouseService.deleteById(houseId);
        houseMasterInfoService.delete(new EntityWrapper<HouseMasterInfo>().eq("house_id",houseId));
        // 同步清除 查询单元楼层户室的缓存
        unitFloorService.clearPreKeyCache("unitHouse:selectUnitFloorHouse");
        return R.ok();
    }

    @ApiOperation(value = "查询户室详情")
    @RequestMapping(value = "/readInfo",method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name="houseId",value="户室id",required = true,dataType = "long",paramType="form"),
    })
    public R readInfo(Long houseId){
        parameterIsNull(houseId,"请选择户室");
        UnitHouse delHouse = unitHouseService.selectById(houseId);
        parameterIsNull(delHouse,"暂无该户室信息");
        return R.ok().put("data",delHouse).putDescription(UnitHouse.class);
    }

    @ApiOperation(value = "改变户室是否在app端显示")
    @RequestMapping(value = "/changeIsShowApp",method =RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name="houseId",value="户室id",required = true,dataType = "long",paramType="form"),
    })
    public R changeIsShowApp(Long houseId) {
        parameterIsNull(houseId,"户室id不能为空");
        UnitHouse unitHouse = unitHouseService.selectById(houseId);
        parameterIsNull(unitHouse,"没有该户室信息");
        if(null==unitHouse.getIsShowApp()||1==unitHouse.getIsShowApp()){
            unitHouse.setIsShowApp(2);
        }else{
            unitHouse.setIsShowApp(1);
        }
        unitHouseService.updateById(unitHouse);
        // 同步清除 查询单元楼层户室的缓存
        unitFloorService.clearPreKeyCache("unitHouse:selectUnitFloorHouse");
        return R.ok();
    }

    @ApiOperation(value = "修改户室信息")
    @RequestMapping(value = "/editHouse",method =RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name="houseId",value="户室id",required = true,dataType = "long",paramType="form"),
           @ApiImplicitParam(name="propertyId",value="物业费模板id",required = false,dataType = "long",paramType="form"),
            @ApiImplicitParam(name="houseRemarks",value="备注信息",required = false,dataType = "string",paramType="form"),
            @ApiImplicitParam(name="isShowApp",value="app是否显示(1-显示，2-不显示)",required = false,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="houseProportion",value="户室面积(/户)",required = false,dataType = "double",paramType="form"),
    })
    public R editHouse(Long houseId, Long propertyId,String houseRemarks,Integer isShowApp,Double houseProportion) {
        parameterIsNull(houseId,"户室id不能为空");
        UnitHouse unitHouse = unitHouseService.selectById(houseId);
        parameterIsNull(unitHouse,"没有该户室信息");
        boolean upTag =false;
        boolean editProportionTag = false;
        if(StringUtils.isNotBlank(houseRemarks)){
            if(houseRemarks.length()>=200){return  R.error(400,"备注信息内容过长");}
            if(! unitHouse.getHouseRemarks().equals(houseRemarks)){
                upTag= true;
                unitHouse.setHouseRemarks(houseRemarks);
            }
        }
        if(null!=isShowApp){
            if(isShowApp==1||isShowApp==2){
                if(isShowApp != unitHouse.getIsShowApp()){
                    upTag= true;
                    unitHouse.setIsShowApp(isShowApp);
                }
            }
        }
        if(null!=houseProportion){
            if(houseProportion<=0){return R.error(400,"户室面积必须大于0");}
            if(houseProportion!=unitHouse.getHouseProportion()){
                upTag= true;
                editProportionTag = true;
                unitHouse.setHouseProportion(houseProportion);
            }
        }
        if(null!=propertyId){
            if(!propertyId.equals(unitHouse.getChargeTemplateId())){
                ChargeTemplate chargeTemplate=  chargeTemplateService.selectById(propertyId);
                if(null==chargeTemplate){return R.error(400,"没有该收费模板信息");}
                upTag = true;
                unitHouse.setChargeTemplateId(propertyId);
                unitHouse.setChargeTemplateName(chargeTemplate.getChargeTemplateName());
                unitHouse.setIsHavaChargeTemplate(1);
            }
        }
        if(upTag){
            unitHouseService.updateById(unitHouse);
            if(editProportionTag){
                HouseMasterInfo editHouseMasterInfo= new HouseMasterInfo();
                editHouseMasterInfo.setHouseProportion(unitHouse.getHouseProportion());
                houseMasterInfoService.update(editHouseMasterInfo,new EntityWrapper<HouseMasterInfo>().eq("house_id",houseId));
            }
        }
        return R.ok();
    }

    @ApiOperation(value = "分页查询户室")
    @RequestMapping(value = "/readPage",method =RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name="pageSize",value="请求条数",required = false,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="pageNum",value="请求页数",required = false,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="communityId",value="社区id",required = false,dataType = "long",paramType="form"),
            @ApiImplicitParam(name="unitId",value="单元id",required = false,dataType = "long",paramType="form"),
            @ApiImplicitParam(name="floorId",value="楼层id",required = false,dataType = "long",paramType="form"),
            @ApiImplicitParam(name="agencyId",value="物业机构id",required = true,dataType = "long",paramType="form"),
            @ApiImplicitParam(name="isShowApp",value="app是否显示(1-显示，2-不显示,3-所有(默认))",required = false,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="isHaveMember",value="查询有无会员认证房屋(1-有，2-无,3-所有(默认))",required = false,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="isHaveMaster",value="查询有无户主信息(1-有，2-无,3-所有(默认))",required = false,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="isHavaChargeTemplate",value="查询是否配置物业费模板(1-是，2-否，3-所有(默认))",required = false,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="sortBy",value="排序显示(1-降序显示(默认),2-升序显示)",required = false,dataType = "int",paramType="form"),
    })
    public R readPage(Integer pageSize,Integer pageNum,Long communityId,Integer isShowApp,Long unitId,Long agencyId
            ,Long floorId,Integer sortBy,Integer isHaveMember,Integer isHaveMaster,Integer isHavaChargeTemplate) {
        parameterIsNull(agencyId,"物业机构id不能为空");
        if(null==pageNum||pageNum<1){pageNum=1;}
        if(null==pageSize||pageSize<1){pageSize=10;}
        Page<UnitHouse> page = new Page<UnitHouse>(pageNum,pageSize);
        Wrapper<UnitHouse> wrapper=  new EntityWrapper<UnitHouse>();
        if(null!=agencyId){
            wrapper.eq("agency_id",agencyId);
        }
        if(null!=communityId){
            wrapper.eq("community_id",communityId);
        }
        if(null!=isShowApp) {
            if (isShowApp == 2 || isShowApp == 1) {
                wrapper.eq("is_show_app", isShowApp);
            }
        }
        if(null!=unitId){
            wrapper.eq("unit_id", unitId);
        }
        if(null!=floorId){
            wrapper.eq("floor_id", floorId);
        }
        if(null!=isHaveMaster){
            if(isHaveMaster==1||isHaveMaster==2){
                wrapper.eq("is_have_master", isHaveMaster);
            }
        }
        if(null!=isHaveMember){
            if(isHaveMember==1||isHaveMember==2){
                wrapper.eq("is_have_member", isHaveMember);
            }
        }
        if(null!=isHavaChargeTemplate){
            if(isHavaChargeTemplate==1||isHavaChargeTemplate==2){
                wrapper.eq("is_hava_charge_template", isHavaChargeTemplate);
            }
        }
        wrapper.orderBy("community_id",false);//默认根据 社区id 降序排序
        wrapper.orderBy("unit_id",false);//默认根据 单元id 降序排序
        wrapper.orderBy("floor_sort",false);//默认根据 楼层id 降序排序
        if(null==sortBy||sortBy!=2){sortBy=1;}//默认根据 序号 降序排序
        if(sortBy ==1){wrapper.orderBy("house_sort",false);}
        if(sortBy ==2){wrapper.orderBy("house_sort",true);}
        Page<UnitHouse> returnPage = unitHouseService.selectPage(page,wrapper);
        return R.ok().put("data",returnPage).putMpPageDescription().putDescription(UnitHouse.class);
    }

    @ApiOperation(value = "户室绑定物业费模板(覆盖原来的)")
    @RequestMapping(value = "/bingChargeTemplateToHouseByHouseId",method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name="houseId",value="户室id",required = true,dataType = "Long",paramType="form"),
            @ApiImplicitParam(name="chargeTemplateId",value="物业费模板id",required = true,dataType = "Long",paramType="form"),
    })
    public R bingChargeTemplateToHouseByHouseId(Long houseId,Long chargeTemplateId){
        parameterIsNull(houseId,"请选择户室");
        UnitHouse house = unitHouseService.selectById(houseId);
        parameterIsNull(house,"没有该户室信息");
        parameterIsNull(chargeTemplateId,"请选择物业费模板");
        ChargeTemplate chargeTemplate =chargeTemplateService.selectById(chargeTemplateId);
        parameterIsNull(chargeTemplate,"没有该物业费模板信息");
        house.setChargeTemplateId(chargeTemplateId);
        house.setChargeTemplateName(chargeTemplate.getChargeTemplateName());
        house.setIsHavaChargeTemplate(1);
        unitHouseService.updateById(house);
        return R.ok();
    }

    @ApiOperation(value = "查询户室")
    @RequestMapping(value = "/readList",method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name="floorId",value="楼层id",required = true,dataType = "Long",paramType="form"),
    })
    public R readList(Long floorId){
        parameterIsNull(floorId,"楼层id不能为空");
        List<UnitHouse> houses = unitHouseService.selectList(new EntityWrapper<UnitHouse>().eq("floor_id",floorId));
        if(houses==null){
            houses = new ArrayList<UnitHouse>();
        }
        return R.ok().put("data",houses).putDescription(UnitHouse.class);
    }
}
